<template>
	<view>
		<!--地图定位主页面-->
		<view class="container">
		  <!-- 地图组件 -->
		  <map
		    id="mainMap"
		    class="map"
		    :latitude="mapCenter.latitude"
		    :longitude="mapCenter.longitude"
		    :scale="mapScale"
		    :markers="markers"
		    :polyline="pathPolyline"
		    :show-location="true"
		    :enable-poi="true"
		    :enable-building="true"
		    @regionchange="onRegionChange"
		    @markertap="onMarkerTap"
		  >
		    <!-- 缩放控件 -->
		    <cover-view class="map-controls">
		      <cover-view class="control-btn" @tap="zoomIn">
		        <cover-view class="control-text">+</cover-view>
		      </cover-view>
		      <cover-view class="control-btn" @tap="zoomOut">
		        <cover-view class="control-text">-</cover-view>
		      </cover-view>
		    </cover-view>
		
		    <!-- 回到当前位置按钮 -->
		    <cover-view class="locate-btn" @tap="moveToCurrentLocation">
		      <cover-view class="locate-text">⊙</cover-view>
		    </cover-view>
		  </map>
		
		  <!-- 底部信息面板 -->
		  <view class="info-panel">
		    <view class="info-item">
		      <text class="info-label">当前位置：</text>
		      <text class="info-value">{{currentAddress || '定位中...'}}</text>
		    </view>
		    <view class="info-item">
		      <text class="info-label">已走距离：</text>
		      <text class="info-value">{{totalDistance}} 米</text>
		    </view>
		    <view class="info-item">
		      <text class="info-label">定位精度：</text>
		      <text class="info-value">{{accuracy}} 米</text>
		    </view>
		  </view>
		
		  <!-- 路径记录控制按钮 -->
		  <view class="action-btns">
		    <button :class="isTracking ? 'action-btn stop' : 'action-btn start'" @tap="toggleTracking">
		      {{isTracking ? '停止记录' : '开始记录'}}
		    </button>
		    <button class="action-btn clear" @tap="clearPath" v-if="pathPoints.length > 0">
		      清除路径
		    </button>
		  </view>
		</view>
		
		<!-- 地理围栏触发弹窗 -->
		<modal
		  :hidden="!showGeofenceModal"
		  title="到达目标位置"
		  confirm-text="知道了"
		  @bindconfirm="closeGeofenceModal"
		>
		  <view class="modal-content">
		    <text>{{geofenceMessage}}</text>
		  </view>
		</modal>
	</view>
</template>

<script>
	// 引入依赖
	const { markersData } = require('../../data/markers');
	const { calculateDistance, isInGeofence } = require('../../utils/geo');
	const { getCurrentLocation, checkLocationAuth, requestLocationAuth, ContinuousLocation } = require('../../utils/location');
	
	// 福州市中心坐标
	const FUZHOU_CENTER = {
	  latitude: 26.0745,
	  longitude: 119.2965
	};
	
	export default {
		data() {
			return {
				// 地图配置
				mapCenter: FUZHOU_CENTER,
				mapScale: 13,
				markers: [],
				
				// 路径记录
				pathPoints: [],
				pathPolyline: [],
				totalDistance: 0,
				
				// 定位状态
				isTracking: false,
				currentAddress: '',
				accuracy: 0,
				
				// 地理围栏
				showGeofenceModal: false,
				geofenceMessage: '',
				triggeredMarkers: new Set(), // 已触发的标记点ID
				
				// 内部状态
				mapContext: null,
				locationService: null
			}
		},
		
		onLoad() {
		  this.initMap();
		  this.loadMarkers();
		  this.requestLocation();
		},
		
		onUnload() {
		  // 页面卸载时停止定位
		  if (this.locationService) {
		    this.locationService.stop();
		  }
		},
		
		methods: {
			/**
			 * 初始化地图
			 */
			initMap() {
			  this.mapContext = wx.createMapContext('mainMap', this);
			},
			
			/**
			 * 加载标记点数据
			 */
			loadMarkers() {
			  const markers = markersData.map(item => ({
			    id: item.id,
			    latitude: item.latitude,
			    longitude: item.longitude,
			    iconPath: item.iconFrames[0], // 先显示第一帧
			    width: 32,
			    height: 32,
			    callout: {
			      content: item.name,
			      color: '#333',
			      fontSize: 14,
			      borderRadius: 5,
			      padding: 5,
			      display: 'BYCLICK'
			    }
			  }));
			  
			  this.markers = markers;
			},
			
			/**
			 * 请求定位权限并获取当前位置
			 */
			async requestLocation() {
			  try {
			    // 检查权限
			    const hasAuth = await checkLocationAuth();
			    if (!hasAuth) {
			      const granted = await requestLocationAuth();
			      if (!granted) {
			        wx.showToast({
			          title: '需要定位权限',
			          icon: 'none'
			        });
			        return;
			      }
			    }
			
			    // 获取当前位置
			    const location = await getCurrentLocation();
			    /* this.setData({
			      mapCenter: {
			        latitude: location.latitude,
			        longitude: location.longitude
			      },
			      accuracy: Math.round(location.accuracy),
			      currentAddress: '福州市'
			    }); */

					this.$set(this.mapCenter, "latitude", location.latitude)
					this.$set(this.mapCenter, "longitude", location.longitude)
					this.accuracy = Math.round(location.accuracy);
					this.currentAddress = '福州市';
			
			    // 移动地图到当前位置（开发者工具中可能不支持，真机测试）
			    try {
			      this.mapContext.moveToLocation();
			    } catch (mapErr) {
			      console.warn('地图移动失败（开发工具限制，真机可正常使用）：', mapErr);
			    }
			
			  } catch (err) {
			    console.error('定位失败：', err);
			    // 定位失败时使用默认的福州中心点
			    console.log('使用默认位置：福州市中心');
			  }
			},
			
			/**
			 * 开始/停止路径记录
			 */
			toggleTracking() {
			  if (this.isTracking) {
			    // 停止记录
			    this.stopTracking();
			  } else {
			    // 开始记录
			    this.startTracking();
			  }
			},
			
			/**
			 * 开始路径记录
			 */
			async startTracking() {
			  // 检查权限
			  const hasAuth = await checkLocationAuth();
			  if (!hasAuth) {
			    wx.showToast({
			      title: '请先授权定位',
			      icon: 'none'
			    });
			    return;
			  }
			
			  // 创建持续定位服务
			  const locationService = new ContinuousLocation({
			    interval: 2000, // 每2秒更新一次
			    onUpdate: (location) => {
			      this.onLocationUpdate(location);
			    },
			    onError: (err) => {
			      console.error('定位错误：', err);
			    }
			  });
			
			  locationService.start();
			
				this.isTracking = true;
				this.locationService = locationService;
			
			  wx.showToast({
			    title: '开始记录路径',
			    icon: 'success'
			  });
			},
			
			/**
			 * 停止路径记录
			 */
			stopTracking() {
			  if (this.locationService) {
			    this.locationService.stop();
			  }
			
				this.isTracking = false;
				this.locationService = null;
			
			  wx.showToast({
			    title: '停止记录',
			    icon: 'success'
			  });
			},
			
			/**
			 * 位置更新回调
			 */
			onLocationUpdate(location) {
			  const { pathPoints } = this;
			  
			  // 如果是第一个点，直接添加
			  if (pathPoints.length === 0) {
			    pathPoints.push(location);
			    this.updatePath(pathPoints);
			    this.checkGeofence(location);
			    return;
			  }
			
			  // 计算与上一个点的距离
			  const lastPoint = pathPoints[pathPoints.length - 1];
			  const distance = calculateDistance(
			    lastPoint.latitude,
			    lastPoint.longitude,
			    location.latitude,
			    location.longitude
			  );
			
			  // 距离大于5米才记录（避免GPS漂移）
			  if (distance >= 5) {
			    pathPoints.push(location);
			    
			    // 更新总距离
			    const totalDistance = this.totalDistance + distance;
					this.totalDistance = Math.round(totalDistance);
			    
			    this.updatePath(pathPoints);
			  }
			
			  // 检查地理围栏
			  this.checkGeofence(location);
			  
			  // 更新精度信息
				this.accuracy = Math.round(location.accuracy);
			},
			
			/**
			 * 更新路径显示
			 */
			updatePath(pathPoints) {
			  const polyline = [{
			    points: pathPoints.map(p => ({
			      latitude: p.latitude,
			      longitude: p.longitude
			    })),
			    color: '#1E90FF',
			    width: 4,
			    dottedLine: false
			  }];
			
				this.pathPoints = pathPoints;
				this.pathPolyline = polyline;
			},
			
			/**
			 * 检查地理围栏触发
			 */
			checkGeofence(userLocation) {
			  const { triggeredMarkers } = this;
			
			  markersData.forEach(marker => {
			    // 如果已经触发过，跳过
			    if (triggeredMarkers.has(marker.id)) {
			      return;
			    }
			
			    // 检查是否进入围栏
			    if (isInGeofence(userLocation, marker, marker.radius)) {
			      // 标记为已触发
			      triggeredMarkers.add(marker.id);
			      
			      // 显示弹窗
						this.showGeofenceModal = true;
						this.geofenceMessage = `您已到达 ${marker.name}\n${marker.description}`;
						this.triggeredMarkers = triggeredMarkers;
			
			      // 震动提示
			      wx.vibrateShort();
			    }
			  });
			},
			
			/**
			 * 关闭地理围栏弹窗
			 */
			closeGeofenceModal() {
				this.showGeofenceModal = false;
			},
			
			/**
			 * 清除路径
			 */
			clearPath() {
			  wx.showModal({
			    title: '确认清除',
			    content: '是否清除当前记录的路径？',
			    success: (res) => {
			      if (res.confirm) {
							this.pathPoints = [];
							this.pathPolyline = [];
							this.totalDistance = 0;
							this.triggeredMarkers = new Set();

			        wx.showToast({
			          title: '路径已清除',
			          icon: 'success'
			        });
			      }
			    }
			  });
			},
			
			/**
			 * 回到当前位置
			 */
			async moveToCurrentLocation() {
			  try {
			    const location = await getCurrentLocation();
			    // 更新地图中心点
					this.$set(this.mapCenter, "latitude", location.latitude);
					this.$set(this.mapCenter, "longitude", location.longitude);

			    // 调用地图API（真机支持）
			    try {
			      this.mapContext.moveToLocation();
			    } catch (mapErr) {
			      console.warn('地图API调用失败（开发工具限制）：', mapErr);
			    }
			  } catch (err) {
			    wx.showToast({
			      title: '获取位置失败',
			      icon: 'none'
			    });
			  }
			},
			
			/**
			 * 地图缩放
			 */
			zoomIn() {
			  const scale = Math.min(this.mapScale + 1, 18);
				this.mapScale = scale;
			},
			
			zoomOut() {
			  const scale = Math.max(this.mapScale - 1, 5);
			  this.mapScale = scale;
			},
			
			/**
			 * 地图区域变化（拖动/缩放）
			 */
			onRegionChange(e) {
			  if (e.type === 'end') {
			    console.log('地图区域改变：', e.detail);
			  }
			},
			
			/**
			 * 标记点点击
			 */
			onMarkerTap(e) {
			  const markerId = e.detail.markerId;
			  const marker = markersData.find(m => m.id === markerId);
			  
			  if (marker) {
			    wx.showModal({
			      title: marker.name,
			      content: marker.description,
			      showCancel: false
			    });
			  }
			}
		}
	}
</script>

<style lang="scss" scoped>
	/* 地图定位主页面样式 */
	
	.container {
	  width: 100%;
	  height: 100vh;
	  position: relative;
	  overflow: hidden;
	}
	
	/* 地图容器 */
	.map {
	  width: 100%;
	  height: 100%;
	}
	
	/* 地图控件 */
	.map-controls {
	  position: absolute;
	  right: 20rpx;
	  top: 50%;
	  transform: translateY(-50%);
	  display: flex;
	  flex-direction: column;
	  gap: 20rpx;
	}
	
	.control-btn {
	  width: 80rpx;
	  height: 80rpx;
	  background: white;
	  border-radius: 50%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.control-text {
	  font-size: 40rpx;
	  font-weight: bold;
	  color: #1E90FF;
	  line-height: 1;
	}
	
	/* 定位按钮 */
	.locate-btn {
	  position: absolute;
	  right: 20rpx;
	  bottom: 300rpx;
	  width: 80rpx;
	  height: 80rpx;
	  background: white;
	  border-radius: 50%;
	  display: flex;
	  align-items: center;
	  justify-content: center;
	  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.1);
	}
	
	.locate-text {
	  font-size: 40rpx;
	  color: #1E90FF;
	  line-height: 1;
	}
	
	/* 底部信息面板 */
	.info-panel {
	  position: absolute;
	  bottom: 160rpx;
	  left: 0;
	  right: 0;
	  background: white;
	  padding: 30rpx;
	  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
	}
	
	.info-item {
	  display: flex;
	  align-items: center;
	  margin-bottom: 15rpx;
	}
	
	.info-item:last-child {
	  margin-bottom: 0;
	}
	
	.info-label {
	  font-size: 28rpx;
	  color: #666;
	  min-width: 150rpx;
	}
	
	.info-value {
	  font-size: 28rpx;
	  color: #333;
	  font-weight: 500;
	  flex: 1;
	  overflow: hidden;
	  text-overflow: ellipsis;
	  white-space: nowrap;
	}
	
	/* 操作按钮 */
	.action-btns {
	  position: absolute;
	  bottom: 40rpx;
	  left: 30rpx;
	  right: 30rpx;
	  display: flex;
	  gap: 20rpx;
	}
	
	.action-btn {
	  flex: 1;
	  height: 80rpx;
	  line-height: 80rpx;
	  border-radius: 40rpx;
	  font-size: 30rpx;
	  font-weight: 500;
	  border: none;
	  text-align: center;
	}
	
	.action-btn.start {
	  background: #1E90FF;
	  color: white;
	}
	
	.action-btn.stop {
	  background: #FF6B6B;
	  color: white;
	}
	
	.action-btn.clear {
	  background: #f5f5f5;
	  color: #666;
	}
	
	/* 弹窗样式 */
	.modal-content {
	  padding: 20rpx;
	  font-size: 30rpx;
	  color: #333;
	  line-height: 1.6;
	  text-align: center;
	}

</style>